package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.fegins.AuthorFegin;
import com.heima.fegins.WemediaFeign;
import com.heima.model.common.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.dtos.AuthDTO;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.model.common.user.pojos.ApUserRealname;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>implements ApUserRealnameService {


    @Override
    public ResponseResult list(AuthDTO dto) {
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Page page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> result = this.page(page, wrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),result.getTotal(),result.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AuthorFegin authorFegin;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        if (dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname apUserRealname = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
        if (apUserRealname==null){
            log.error("待审核 实名认证信息不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId,apUserRealname.getUserId()));
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apUserRealname.setStatus(status);
        apUserRealname.setCreatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);
        if (AdminConstants.PASS_AUTH.equals(status)){
            WmUser wmUser=createWmUser(apUser);
//            System.out.println(1/0);
            createApAuthor(apUser,wmUser);
        }
        return ResponseResult.okResult();
    }

    private void createApAuthor(ApUser apUser,WmUser wmUser) {
        ResponseResult<ApAuthor> apAuthor = authorFegin.findByUserId(apUser.getId());
        if (apAuthor.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        ApAuthor data = apAuthor.getData();
        if (data!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        ApAuthor author=new ApAuthor();
        author.setCreatedTime(new Date());
        author.setName(apUser.getName());
        author.setType(2); // 自媒体人类型
        author.setUserId(apUser.getId()); // APP 用户ID
        author.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult<ApAuthor> result = authorFegin.save(author);
        if (result.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    private WmUser createWmUser(ApUser apUser) {
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        wmUser=new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setNickname(apUser.getName());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setStatus(9);
        wmUser.setApUserId(apUser.getId());
        ResponseResult<WmUser> wmUserResponseResult = wemediaFeign.save(wmUser);
        if (wmUserResponseResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return wmUserResponseResult.getData();
    }
}
